/**
 * 页面交互相关，放在index.js
 */
import { $config } from "@/config.js";
import mixin from "./mixin";
let isNoFileType = ['css','html','php','js']
export default {
  mixins: [mixin],
  data() {
    return {
      formData: {
        content: ""
      },
      baseUrl: $config.customerService.baseUrl,
      userAvatar: "/assets/images/index/avatar-red2.png",
      chatBgImg:
        "http://img.bq233.com/kanqq/pic/upload/2018/0719/1531984077164961.jpg",
      isloading: true, //标识是否正在获取数据
      imgHeight: "1000px",
      mpInputMargin: false, //适配微信小程序 底部输入框高度被顶起的问题
      chatType: "voice", // 图标类型 'voice'语音 'keyboard'键盘
      voiceTitle: "按住 说话",
      Recorder: uni.getRecorderManager(),
      Audio: uni.createInnerAudioContext(),
      recording: false, //标识是否正在录音
      isStopVoice: false, //加锁 防止点击过快引起的当录音正在准备(还没有开始录音)的时候,却调用了stop方法但并不能阻止录音的问题
      voiceInterval: null,
      voiceTime: 0, //总共录音时长
      canSend: true, //是否可以发送
      PointY: 0, //坐标位置
      voiceIconText: "正在录音...",
      showFunBtn: false, //是否展示功能型按钮
      AudioExam: null, //正在播放音频的实例
      funList: [
        { icon: "icon-img", title: "照片", uploadType: ["album"] },
        { icon: "icon-photograph", title: "拍摄", uploadType: ["camera"] },
        { icon: "icon-file", title: "文件", uploadType: ["file"] }
      ]
    };
  },
  computed: {},
  methods: {
    //处理滚动
    bindScroll(sel, duration = 0) {
      const query = uni.createSelectorQuery().in(this);
      query
        .select(sel)
        .boundingClientRect(data => {
          uni.pageScrollTo({
            scrollTop: data && data.top - 40,
            duration
          });
        })
        .exec();
    },
    //切换语音或者键盘方式
    switchChatType(type) {
      this.chatType = type;
      this.showFunBtn = false;
    },
    //切换功能性按钮
    switchFun() {
      // this.chatType = "keyboard";
      this.showFunBtn = !this.showFunBtn;
      uni.hideKeyboard();
    },
    //用户触摸屏幕的时候隐藏键盘
    touchstart() {
      uni.hideKeyboard();
    },
    //准备开始录音
    startVoice(e) {
      if (!this.Audio.paused) {
        //如果音频正在播放 先暂停。
        this.stopAudio(this.AudioExam);
      }
      this.recording = true;
      this.isStopVoice = false;
      this.canSend = true;
      this.voiceIconText = "正在录音...";
      this.PointY = e.touches[0].clientY;
      this.Recorder.start({
        format: "mp3"
      });
    },
    //录音已经开始
    beginVoice() {
      if (this.isStopVoice) {
        this.Recorder.stop();
        return;
      }
      this.voiceTitle = "松开 结束";
      this.voiceInterval = setInterval(() => {
        this.voiceTime++;
      }, 1000);
    },
    //move 正在录音中
    moveVoice(e) {
      const PointY = e.touches[0].clientY;
      const slideY = this.PointY - PointY;
      if (slideY > uni.upx2px(120)) {
        this.canSend = false;
        this.voiceIconText = "松开手指 取消发送 ";
      } else if (slideY > uni.upx2px(60)) {
        this.canSend = true;
        this.voiceIconText = "手指上滑 取消发送 ";
      } else {
        this.voiceIconText = "正在录音... ";
      }
    },
    //结束录音
    endVoice() {
      this.isStopVoice = true; //加锁 确保已经结束录音并不会录制
      this.Recorder.stop();
      this.voiceTitle = "按住 说话";
    },
    //录音被打断
    cancelVoice(e) {
      this.voiceTime = 0;
      this.voiceTitle = "按住 说话";
      this.canSend = false;
      this.Recorder.stop();
    },
    //处理录音文件
    handleRecorder({ tempFilePath, duration }) {
      let contentDuration;
      // #ifdef MP-WEIXIN
      this.voiceTime = 0;
      if (duration < 600) {
        this.voiceIconText = "说话时间过短";
        setTimeout(() => {
          this.recording = false;
        }, 200);
        return;
      }
      contentDuration = duration / 1000;
      // #endif

      // #ifdef APP-PLUS
      contentDuration = this.voiceTime + 1;
      this.voiceTime = 0;
      if (contentDuration <= 0) {
        this.voiceIconText = "说话时间过短";
        setTimeout(() => {
          this.recording = false;
        }, 200);
        return;
      }
      // #endif

      this.recording = false;
      const params = {
        contentType: 2,
        content: tempFilePath,
        contentDuration: Math.ceil(contentDuration)
      };
      this.canSend && this.sendMsg(params);
    },
    //控制播放还是暂停音频文件
    handleAudio(item) {
      this.AudioExam = item;
      this.Audio.paused ? this.playAudio(item) : this.stopAudio(item);
    },
    //播放音频
    playAudio(item) {
      this.Audio.src = item.content;
      this.Audio.hasBeenSentId = item.hasBeenSentId;
      this.Audio.play();
      item.anmitionPlay = true;
    },
    //停止音频
    stopAudio(item) {
      item.anmitionPlay = false;
      this.Audio.src = "";
      this.Audio.stop();
    },
    //关闭动画
    closeAnmition() {
      const hasBeenSentId = this.Audio.hasBeenSentId;
      const item = this.messageList.find(
        it => it.hasBeenSentId == hasBeenSentId
      );
      item.anmitionPlay = false;
    },
    //点击宫格时触发
    clickGrid(index) {
      if (index == 0) {
        this.chooseImage(["album"]);
      } else if (index == 1) {
        this.chooseImage(["camera"]);
      } else if (index==2) {
        this.sendFile();
      }
    },
    //判断文件类型
    decideFileType(data){
      let result = isNoFileType.indexOf(data)
      if(result==-1){
        return false;
      }else{
        return true;
      }
    },
    //发送文件
    sendFile(){
      let imageList=[]
      uni.chooseImage({
         sizeType: ['original', 'compressed'],
         success: (res) => {
            var formData = new FormData();
            uni.showLoading({ title: "上传中..." });
            let files = new window.File([res.tempFilePaths[0]], res.tempFiles[0].name, {type: res.tempFiles[0].type})
            uni.uploadFile({
              url: this.baseUrl + "/admin/event/uploadfile",
              header: {
                Accept: "application/json, text/javascript, */*; q=0.01",
                "X-Requested-With": "XMLHttpRequest"
              },
              formData: {
                folder:files,
                visiter_id: 'Xvxg6qMi',
                business_id: "tysh",
                avatar: this.userAvatar,
                record: "",
                service_id: this.connection.service_id
              },
              success: (resp) => {
                let params = {
                  contentType: 4,
                  cid: Date.now(),
                  name:res.tempFiles[0].name,
                  baseUrl:JSON.parse(resp.data).data
                };
                this.sendMsg(params);
                uni.hideLoading();
              }
            })
         },
      })
    },
    //发送图片
    chooseImage(sourceType) {
      uni.chooseImage({
        sourceType,
        sizeType: ["compressed"],
        success: res => {
          this.showFunBtn = false;
          const tempFilePaths = res.tempFilePaths;
          uni.showLoading({ title: "上传中..." });
          for (let i = 0; i < res.tempFilePaths.length; i++) {
            uni.uploadFile({
              url: this.baseUrl + "/admin/event/upload",
              filePath: tempFilePaths[i],
              name: "upload",
              header: {
                Accept: "application/json, text/javascript, */*; q=0.01",
                "X-Requested-With": "XMLHttpRequest"
              },
              formData: {
                visiter_id: this.user.uuid,
                business_id: "tysh",
                avatar: this.userAvatar,
                record: "",
                service_id: this.connection.service_id
              },
              success: res => {
                let params = {
                  contentType: 3,
                  cid: Date.now()
                };
                let srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i; //i忽略大小写 括号中内容放到内存中
                var src = res.data.match(srcReg);
                params.content = src[1];
                this.sendMsg(params);
              }
            });
            uni.hideLoading();
          }
        }
      });
    },
    //查看大图
    viewImg(imgList) {
      uni.previewImage({
        urls: imgList,
        // #ifndef MP-WEIXIN
        indicator: "number"
        // #endif
      });
    }
  },
  async onLoad() {
    this.initData();
    //录音开始事件
    this.Recorder.onStart(e => {
      this.beginVoice();
    });
    //录音结束事件
    this.Recorder.onStop(res => {
      clearInterval(this.voiceInterval);
      this.handleRecorder(res);
    });

    //音频停止事件
    this.Audio.onStop(e => {
      this.closeAnmition();
    });

    //音频播放结束事件
    this.Audio.onEnded(e => {
      this.closeAnmition();
    });
  },
  onReady() {
    uni.getSystemInfo({
      success: res => {
        this.imgHeight = res.windowHeight + "px";
      }
    });

    uni.onKeyboardHeightChange(res => {
      if (res.height == 0) {
        // #ifdef MP-WEIXIN
        this.mpInputMargin = false;
        // #endif
      } else {
        this.showFunBtn = false;
      }
    });
  }
};
